    /**
 * Author: w景洋.
 * Time: 2016/4/29 0029
 */
angular.module('service.payment',[
    'ngResource',
    "ngStorage"
])

//微信支付的接口
.service('WxpayService', ['$resource','$localStorage',function ($resource, $localStorage){
    var openid_res = $resource(pay_config.wxpay_reaurl + "openid");
    var jsapipay_res = $resource(mallurl +"orderspay/wxjsapipay/"+ pay_config.wxpay_spid + "/:openid");
    var WxpayService = this;
    var $storage = $localStorage;

    this.pay = function(payInfo, success_func, error_func){

        if (!$storage.cmtwxpay_openid) {
            var reg = new RegExp("(^|&)" + "code" + "=([^&]*)(&|$)");
            var r = window.location.search.substr(1).match(reg);
            var authcode = "xxxxxxxxxxxxxxxxxx";
            if (r) {
                 authcode = unescape(r[2]);
            }
            openid_res.get({wxspid:pay_config.wxpay_spid, code:authcode}).$promise.then(function(data){

                if (data.openid) {
                    $storage.cmtwxpay_openid = data.openid;
                    payInfo.openid = data.openid;
                    WxpayService.wxpayjsapipay(payInfo, success_func, error_func);
                } else {
                    var jump_url = "https://open.weixin.qq.com/user/oauth2/authorize?appid="
                      +pay_config.wxpay_appid+"&redirect_uri="+pay_config.wxpay_backurl
                      +"&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect";
                    window.location.href = jump_url;
                }
            }, function(error){
                //alert(error);
            });
        }
        else {
            payInfo.openid = $storage.cmtwxpay_openid;
            //支付调起
            return WxpayService.wxpayjsapipay(payInfo, success_func, error_func);
        }
    }

    this.wxpayjsapipay = function(payInfo, success_func, error_func) {
        //支付调起
        return jsapipay_res.save({openid:payInfo.openid},payInfo, success_func, error_func);
    }
}])

    //支付宝手机网页支付
    .service('AliWapPay', ['$resource','$http','$q',function ($resource,$http,$q){
        //预支付
        this.wapPay = function (data) {
            data.show_url = pay_config.alipay_callback;
            var deferred = $q.defer();
            $http({
                method: "POST",
                url: pay_config.alipay_url+pay_config.alipay_appid,
                data: data
            }).success(function(data,status,headers,config){
                deferred.resolve(data);
            }).error(function(data,status,headers,config){
                deferred.reject(data);
            });
            return deferred.promise;
        };

    }])